package logic

import (
	"context"
	"github.com/pkg/errors"
	"go-zero-demo/apps/user/model"
	"go-zero-demo/common/utils"
	"go-zero-demo/common/xerr"
	"time"

	"go-zero-demo/apps/user/cmd/rpc/internal/svc"
	"go-zero-demo/apps/user/cmd/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

var ErrUserAlreadyRegister = xerr.NewErrMsg("user has been registered")

var DefaultAvatarUrl = "https://xxx.png"

type RegisterUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserLogic {
	return &RegisterUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,

		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterUserLogic) RegisterUser(in *pb.RegisterUserReq) (*pb.RegisterUserResp, error) {

	// 参数校验
	if in == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PB_CHECK_ERR), "Register user empty param")
	}
	if len(in.GetUsername()) == 0 || len(in.GetPassword()) == 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PB_CHECK_ERR), "Register user error param")
	}

	if existUser := l.svcCtx.UserModel.CheckUsernameExist(l.ctx, in.GetUsername()); existUser {
		return nil, errors.Wrapf(ErrUserAlreadyRegister, "register user exists username: %s", in.GetUsername())
	}

	// 插入用户
	newUser := &model.User{
		Username:   in.GetUsername(),
		Password:   utils.Md5ByString(in.GetPassword()),
		Avatar:     DefaultAvatarUrl,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}
	userId, err := l.svcCtx.UserModel.Create(l.ctx, newUser)
	if userId == 0 || err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_INSERT_ERR), "insert user failed, username: %s, password: %s", in.GetUsername(), in.GetPassword())
	}

	// 生成token
	generateTokenLogic := NewGenerateTokenLogic(l.ctx, l.svcCtx)
	tokenResp, err := generateTokenLogic.GenerateToken(&pb.GenerateTokenReq{UserId: userId})
	if err != nil {
		return nil, errors.Wrapf(ErrGenerateTokenError, "Generate token failed, user_id: %d", userId)
	}

	return &pb.RegisterUserResp{
		AccessToken:  tokenResp.AccessToken,
		ExpireTime:   tokenResp.ExpireTime,
		RefreshAfter: tokenResp.RefreshAfter,
	}, nil
}
